package com.vay.de.dang.online.util;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.Base64;

import androidx.exifinterface.media.ExifInterface;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.vay.de.dang.online.VnApp;
import com.vay.de.dang.online.R;
import com.vay.de.dang.online.entiy.PropertyRuleEntity;
import com.vay.de.dang.online.entiy.RuleNotEmptyEntity;
import com.vay.de.dang.online.entiy.RuleRegexpEntity;
import com.vay.de.dang.online.entiy.RuleStringLengthEntity;
import com.vay.de.dang.online.view.VnItemLayout;

import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Collection;

public final class VnUtil {

    final static NumberFormat MoneyF1 = new DecimalFormat("#,##0.00");
    final static NumberFormat MoneyF2 = new DecimalFormat("#,###");

    public static boolean isEmpty(Collection<?> list) {
        return list == null || list.isEmpty();
    }

    public static boolean isEmpty(String text) {
        return TextUtils.isEmpty(text);
    }

    public static int toIntValue(String value) {
        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static boolean isRuleOk(VnItemLayout itemLayout, PropertyRuleEntity rule) {
        String str = itemLayout.getContent();
        if (rule != null) {
            RuleNotEmptyEntity notEmpty = rule.getNotEmpty();
            RuleStringLengthEntity stringLength = rule.getStringLength();
            RuleRegexpEntity regexp = rule.getRegexp();
            if (notEmpty != null) {
                if (isEmpty(str)) {
                    itemLayout.showWarring(notEmpty.getMessage());
                    return false;
                }
            }

            if (stringLength != null) {
                int size = str.length();
                if (size < stringLength.getMin() || size > stringLength.getMax()) {
                    itemLayout.showWarring(stringLength.getMessage());
                    return false;
                }
            }

            if (regexp != null) {
                if (!str.matches(regexp.getRegexp())) {
                    itemLayout.showWarring(regexp.getMessage());
                    return false;
                }
            }
        } else {
            if (isEmpty(str)) {
                itemLayout.showWarring("Not Empty");
                return false;
            }
        }

        itemLayout.showWarring("");

        return true;
    }

    public static boolean isDropList(VnItemLayout itemLayout, String error) {
        String str = itemLayout.getContent();
        if (isEmpty(str)) {
            itemLayout.showWarring(error);
            return false;
        }
        itemLayout.showWarring("");
        return true;
    }

    public static void recyBitmap(Bitmap des) {
        try {
            if (des != null && !des.isRecycled()) {
                des.recycle();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Bitmap clipBitmap(Bitmap src, Rect rect) {
        Bitmap out = Bitmap.createBitmap(src, rect.left, rect.top, rect.width(), rect.height());
        if (out != src) recyBitmap(src);
        return out;
    }

    public static String saveBitmapFile(Bitmap src) {
        return saveBitmapFile(src, 0);
    }

    public static String saveBitmapFile(Bitmap src, int degree) {
        try {
            Context context = VnContext.instance().getContext();
            File dir = context.getFilesDir();
            File root = new File(dir, "ImageCache");
            if (!root.exists()) {
                root.mkdir();
            }

            Bitmap dest = src;
            if (src.getHeight() > 1080) {
                dest = Bitmap.createScaledBitmap(src, 1280, 720, true);
            }

            // 旋转
            if (degree > 0) {
                dest = rotateImage(dest, degree);
            }

            if (dest != src) {
                // src.recycle();
            }

            File file = new File(root, "takeImage_" + System.currentTimeMillis() + ".jpg");
            FileOutputStream out = new FileOutputStream(file);
            dest.compress(Bitmap.CompressFormat.JPEG, 80, out);
            out.flush();
            out.close();
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Bitmap rotateImageIfRequired(Bitmap img, String path) {
        try {
            ExifInterface ei = new ExifInterface(path);
            int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    return rotateImage(img, 90);
                case ExifInterface.ORIENTATION_ROTATE_180:
                    return rotateImage(img, 180);
                case ExifInterface.ORIENTATION_ROTATE_270:
                    return rotateImage(img, 270);
                default:
                    return img;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Bitmap rotateImage(Bitmap img, int degree) {
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0,
                img.getWidth(), img.getHeight(), matrix, true);
        img.recycle();
        return rotatedImg;
    }

    public static void deleteCache() {
        try {
            Context context = VnContext.instance().getContext();
            File dir = context.getFilesDir();
            File root = new File(dir, "ImageCache");
            File[] files = root.listFiles();
            if (files != null) {
                for (File f : files) {
                    f.delete();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String toTwoStr(int value) {
        return value > 9 ? String.valueOf(value) : "0" + value;
    }

    public static String toMoneyStr1(float value) {
        return VnApp.getStr(R.string.label_money) + " " + MoneyF1.format(value);
    }

    public static String toMoneyStr2(float value) {
        return VnApp.getStr(R.string.label_money) + " " + MoneyF2.format((int) value);
    }

    public static String toPhase(String phase) {
        if ("1".equals(phase)) {
            return "1st Repayment";
        } else if ("2".equals(phase)) {
            return "2nd Repayment";
        } else if ("3".equals(phase)) {
            return "3rd Repayment";
        } else if ("4".equals(phase)) {
            return "Fourth Repayment";
        } else {
            return phase + " Repayment";
        }
    }

    public static Bitmap newQRCode(String content, int width, int height) {
        return newQRCode(BarcodeFormat.QR_CODE, content, width, height);
    }

    public static Bitmap newQRCode(BarcodeFormat format, String content, int width, int height) {
        if (isEmpty(content)) return null;
        try {
            MultiFormatWriter writer = new MultiFormatWriter();
            BitMatrix matrix = writer.encode(content, format, width, height);
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (matrix.get(x, y)) {
                        pixels[y * width + x] = Color.BLACK;
                    } else {
                        pixels[y * width + x] = Color.WHITE;
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void copyTextClip(String label, String text) {
        ClipboardManager clipboardManager = (ClipboardManager) VnApp.instance().getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText(label, text);
        clipboardManager.setPrimaryClip(clipData);
    }

    public static Bitmap decodeBitmapByBase64(String base64) {
        try {
            byte[] data = Base64.decode(base64, Base64.DEFAULT);
            if (data != null) {
                return BitmapFactory.decodeByteArray(data, 0, data.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int toVersionName(String versionName) {
        try {
            return Integer.parseInt(versionName.replaceAll("\\.", ""));
        } catch (Exception e) {
            return -1;
        }
    }
}
